package com.scedu.controller;




import com.scedu.entity.User;

import com.scedu.exception.CommonException;
import com.scedu.result.ProfileResult;
import com.scedu.result.ResultBody;
import com.scedu.result.ResultCode;
import com.scedu.service.UserService;
import com.scedu.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sc
 * @since 2020-04-21
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public ResultBody Login(@RequestParam(value = "username",required = false) String username,
                            @RequestParam(value = "password",required = false) String password)
    //public ResultBody Login(@RequestParam(@RequestBody Map<String ,String> loginmap)
    {
//        String username =loginmap.get("username");
//        String password =loginmap.get("password");
        log.info("控制器 username={} password={}", username,password);
        User user= userService.findByUserName(username);
        if(user==null||!user.getPassword().equals(password)){
            //登录失败
            return ResultBody.loginFailed();
        }
        //登录成功
        Map<String,Object> map= new HashMap<>();
        map.put("realname", user.getRealname());
        map.put("sex", user.getSex());
        String jwt = jwtUtils.createJwt(user.getId(), user.getUsername(), map);

        return ResultBody.success(jwt);
    }

    @PostMapping("/profile")
    public ResultBody profile(HttpServletRequest request) throws Exception
    {
        /*1.从请求头信息中获取TOKEN数据
           1.1获取请求头信息，名称=Authorization
           1.2替换 Bear+空格
           1.3 解析token
           1.4 获取claims
         */
        String authorization = request.getHeader("Authorization"); //1.1获取请求头信息，名称=Authorization

        if (StringUtils.isEmpty(authorization)){
            //没有Authorization授权信息
            log.info("没有Authorization授权信息");
            throw new CommonException(ResultCode.UNAUTHORIZED);

        }
        authorization=authorization.replace("Bear ", ""); //1.2替换 Bear+空格
        //1.3 解析token
        Claims claims = jwtUtils.parseJwt(authorization);

        String userId= claims.getId();

        User user= userService.getById(userId); //根据id查询用户基本信息
        ProfileResult profileResult = userService.CreateProfileResult(user); //1.4 获取claims
        return ResultBody.success(profileResult);

    }
}
